import { getToken } from '@/utils/token'
import { Toast } from 'vant'
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/article' },
    {
      name: 'layout',
      path: '/',
      component: () => import('@/views/layout.vue'),
      children: [
        {
          name: 'article',
          path: 'article',
          component: () => import('@/views/article.vue')
        },
        {
          name: 'collect',
          path: 'collect',
          component: () => import('@/views/collect.vue')
        },
        {
          name: 'like',
          path: 'like',
          component: () => import('@/views/like.vue')
        },
        {
          name: 'user',
          path: 'user',
          component: () => import('@/views/user.vue')
        }
      ]
    },
    {
      name: 'detail',
      path: '/detail/:id',
      component: () => import('@/views/article-detail.vue')
    },
    {
      name: 'login',
      path: '/login',
      component: () => import('@/views/MyLogin.vue')
    },
    {
      name: 'register',
      path: '/register',
      component: () => import('@/views/register.vue')
    }
  ]
})

// 路由白名单
const whiteList = ['/login', '/register']

router.beforeEach((to, from, next) => {
  if (whiteList.includes(to.path)) {
    next()
  } else {
    if (getToken()) {
      next()
    } else {
      Toast('请登录')
      next('/')
    }
  }
})
export default router
